package com.itcm.tcpdemo.components;

import com.itcm.tcpdemo.model.Packet;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

public class PacketHeaderDecoder extends ByteToMessageDecoder {

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        if (in.readableBytes() >= 8) { // 确保有足够的数据读取包头
            int readerIndex = in.readerIndex();
            byte protocolVersion = in.readByte();
            byte messageType = in.readByte();
            byte flags = in.readByte();
            in.skipBytes(1); // 跳过保留字段
            int dataLength = in.readInt();

            if (in.readableBytes() >= dataLength) { // 确保有足够的数据读取包体
                // 创建一个新的 ByteBuf 来包含整个数据包
                ByteBuf fullPacket = in.slice(readerIndex, 8 + dataLength);
                Packet packet = Packet.fromByteBuf(fullPacket.retain());
                out.add(packet);

                // 移动读取索引以跳过已处理的数据
                in.readerIndex(readerIndex + 8 + dataLength);
            } else {
                in.readerIndex(readerIndex); // 如果没有足够的数据，回滚读取索引
            }
        }
    }
}
